<html>
<head>
<title>PCBits Online Shop</title>
<?php
	/*
	 * Database constants
	 */
	$db_host = "manning.cs.jcu.edu.au";
	$db_user = "cp3003jcxxxxxx";
	$db_pass = "jcxxxxxx";
	$db_name = "jcxxxxxx";

	/*
	 * Where html and php files are stored
	 */
	$form = "http://manning.cs.jcu.edu.au/~jcxxxxxx/pcbits/aisle.php";

	function hiddenState($price, $spent) {
		printf("<input type=\"hidden\" name=\"price\" value=\"%d\">\n",
			$price);
		printf("<input type=\"hidden\" name=\"spent\" value=\"%d\">\n",
			$spent);
	}

	function productTableHead() {
		printf("<table border=\"1\" cellpadding=\"0\">\n");
		printf("<tr>\n");
		printf("	<th>SKU</th>\n");
		printf("	<th>Manufacturer</th>\n");
		printf("	<th>Description</th>\n");
		printf("	<th>Price</th>\n");
		printf("	<th>Quantity</th>\n");
		printf("</tr>\n\n");
	}

	function productTableEntry($sku, $mfr, $dsc, $prc, $aisle, $spent) {
		printf("<tr>\n");
		printf("	<th>%s</th>\n", $sku);
		printf("	<th>%s</th>\n", $mfr);
		printf("	<th>%s</th>\n", $dsc);
		printf("	<th>%d.%02d</th>\n", $prc/100, $prc%100);
		printf("	<td align=\"center\">\n");

		printf("<form action=\"%s\" method=\"GET\">", $form);
		printf("<input type=\"text\" name=\"quantity\" value=\"0\">");
		printf("<input type=\"submit\" name=\"Buy!\">");
		printf("<input type=\"hidden\" name=\"aisle\" value=\"%s\">",
			$aisle);
		hiddenState($prc, $spent);
		printf("</form>\n");
		printf("</td>\n");
		printf("</tr>\n\n");
	}

	function productTableTail() {
		printf("</table>\n");
	}

	function debug($argv) {
		printf("<hr />\n");
		while (list($index, $value) = each($argv)) {
			printf("argv[%d]=%s\n", $index, $value);
		}
		printf("<hr />\n");
	}

	$aisle = $_REQUEST["aisle"];
	$price = $_REQUEST["price"];
	$quantity = $_REQUEST["quantity"];
	$spent = $_REQUEST["spent"];

	if (!isset($aisle)) {
		$aisle = "Processor";
	}

	$spent += $quantity * $price;
?>
</head>

<body>
<!-- Navbar selects aisle -->
<form action=<?php print('"'.$form.'"'); ?> method="GET">
	<table>
	<tr>
	<td><input type="submit" name="aisle" value="Processor"></td>
	<td><input type="submit" name="aisle" value="Motherboard"></td>
	<td><input type="submit" name="aisle" value="Memory"></td>
	</tr>
	</table>
	<?php hiddenState(0, $spent); ?>
</form>

<?php
	printf("Welcome to the %s aisle.  ", $aisle);
	printf("You've already spent $%d.%02d<br />\n",
		$spent/100, $spent%100);
	$dbc = mysql_connect($db_host, $db_user, $db_pass)
		or die("Cannot connect to database");
	mysql_select_db($db_name, $dbc)
		or die("Cannot select database");
	$query = sprintf("select * from products where type=\"%s\"", $aisle);
	printf("query is [%s]<br />\n", $query);
	$result = mysql_query($query)
		or die("Query failed");
	productTableHead();
	while ($r = mysql_fetch_array($result, MYSQL_ASSOC)) {
		productTableEntry(
			$r["sku"],
			$r["manufacturer"],
			$r["description"],
			$r["price"],
			$aisle,
			$spent
		);
	}
	productTableTail();
	mysql_close($dbc);
?>
<hr />
</body>
</html>
